package com.netolobo.blogspot.lights;


import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.netolobo.blospot.crud.DbAdapter;

public class Principal extends Activity {
    /** Called when the activity is first created. */
	private ImageView square [][];
	private static final String PRINCIPAL = "principal";
	final int ON  =  1;
    final int OFF = -1;
    protected int light[][] = new int[5][5];
    protected int counterOn  = 0;
    protected int counterOff = 0;
    int end = 0;
    int countSquare = 0;
    private Button restart;
    private TextView valueOn, valueOff;
    private Chronometer chronometer;
    static Long mRowId;
	static DbAdapter mDbHelper;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        try {//abrindo o banco de dados
			mDbHelper = new DbAdapter(this);

			mDbHelper.open();

		} catch (Exception e) {
			Log.v(PRINCIPAL, " "+e);
		}
        
        
        chronometer = (Chronometer) findViewById(R.id.chronometer);
        
        valueOn = (TextView) findViewById(R.id.valor_acesas);
        valueOff = (TextView) findViewById(R.id.valor_apagado);
        
        square = new ImageView[5][5];
        
        square [0][0] = (ImageView) findViewById(R.id.s1);
        square [0][1] = (ImageView) findViewById(R.id.s2);
        square [0][2] = (ImageView) findViewById(R.id.s3);
        square [0][3] = (ImageView) findViewById(R.id.s4);
        square [0][4] = (ImageView) findViewById(R.id.s5);
        
        square [1][0] = (ImageView) findViewById(R.id.s6);
        square [1][1] = (ImageView) findViewById(R.id.s7);
        square [1][2] = (ImageView) findViewById(R.id.s8);
        square [1][3] = (ImageView) findViewById(R.id.s9);
        square [1][4] = (ImageView) findViewById(R.id.s10);
        
        square [2][0] = (ImageView) findViewById(R.id.s11);
        square [2][1] = (ImageView) findViewById(R.id.s12);
        square [2][2] = (ImageView) findViewById(R.id.s13);
        square [2][3] = (ImageView) findViewById(R.id.s14);
        square [2][4] = (ImageView) findViewById(R.id.s15);
        
        square [3][0] = (ImageView) findViewById(R.id.s16);
        square [3][1] = (ImageView) findViewById(R.id.s17);
        square [3][2] = (ImageView) findViewById(R.id.s18);
        square [3][3] = (ImageView) findViewById(R.id.s19);
        square [3][4] = (ImageView) findViewById(R.id.s20);
        
        square [4][0] = (ImageView) findViewById(R.id.s21);
        square [4][1] = (ImageView) findViewById(R.id.s22);
        square [4][2] = (ImageView) findViewById(R.id.s23);
        square [4][3] = (ImageView) findViewById(R.id.s24);
        square [4][4] = (ImageView) findViewById(R.id.s25);
        
        restart = (Button) findViewById(R.id.bRestart);
        
        
        start();
        
        
        
        restart.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				chronometer.stop();
				chronometer.setBase(SystemClock.elapsedRealtime());//resetar o cronometro
				start();
				//FIXME: FAZER FUNCIONAR O CRONOMETRO NO FORMATO HH:MM:SS chronometer.setFormat("%s");
				dialogVictory();
				
			}
		});
        
        square [0][0].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(0, 0);
					
				countLight();
				paint();
			}
		});
        
        square [0][1].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
	
				calclado(0, 1);				

				countLight();				
				paint();
			}
		});
        
        square [0][2].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(0, 2);				

				countLight();				
				paint();
			}
		});
        
        square [0][3].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(0, 3);

				countLight();				
				paint();
			}
		});
        
        square [0][4].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(0, 4);			

				countLight();				
				paint();
			}
		});
        
        square [1][0].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(1, 0);				

				countLight();
				paint();
			}
		});
        
        square [1][1].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(1, 1);


				countLight();
				paint();
			}
		});
        
        square [1][2].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(1, 2);

				

				countLight();
				paint();
			}
		});
        
        square [1][3].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(1, 3);				
				

				countLight();
				paint();
			}
		});
        
        square [1][4].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(1, 4);

				
				countLight();
				paint();
			}
		});
        
        square [2][0].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(2, 0);				


				countLight();
				paint();
			}
		});
        
        square [2][1].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(2, 1);				

				countLight();
				paint();
			}
		});
        
        square [2][2].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(2, 2);

				countLight();
				paint();
			}
		});
        
        square [2][3].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {

				calclado(2, 3);
				
				countLight();
				paint();
			}
		});
        
        square [2][4].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(2, 4);				

				countLight();								
				paint();
			}
		});
        
        
        square [3][0].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(3, 0);				

				countLight();								
				paint();
			}
		});
        
        square [3][1].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(3, 1);				

				countLight();								
				paint();
			}
		});
        
        square [3][2].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(3, 2);				

				countLight();								
				paint();
			}
		});
        
        square [3][3].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(3, 3);				

				countLight();								
				paint();
			}
		});
        
        square [3][4].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(3, 4);					

				countLight();								
				paint();
			}
		});
        
        square [4][0].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(4, 0);		

				countLight();								
				paint();
			}
		});     
        
        square [4][1].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(4, 1);

				countLight();
				paint();
			}
		});
        
        square [4][2].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(4, 2);

				countLight();
				paint();
			}
		});
        
        square [4][3].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(4, 3);

				countLight();
				paint();
			}
		});
        
        square [4][4].setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				calclado(4, 4);

				countLight();								
				paint();
			}
		});
        
    }
    
    /**
     * Método responsável por zera a matrix
     */
    public void init() {
    	end = 0;

        for (int i = 0; i < 5; i++) {
             for (int j = 0; j < 5; j++) {
                  light[i][j] = OFF;
             }
        }
        countLight();
   }
    
    /**Método responsável por iniciar ou reiniciar o jogo
     * 
     */
    public void start() {
        init();
        //chronometer.setFormat("hh:mm:ss");
        chronometer.start();
        
        paint();
        
        //dialogVictory();//testando o dialogo de vitoria
   }
    
    /**
     * Método responsavel por colororir todos os quadros da tela de acordo com seus valores
     */
    public void paint() {
        
        for (int i = 0; i < 5; i++) {
             for (int j = 0; j < 5; j++) {
            	  //Log.v(PRINCIPAL, "valor de light no paint"+i+" "+j+" = "+light[i][j]);
                  if (light[i][j]  != 0) {
                       drawLight(i, j);
                  }
             }
        }
   }
    
    /**
     * Método que pinta um quadro da matrix (on ou off) de acordo com as coordenadas passadas
     * @param column
     * @param row
     */
    public void drawLight(int column, int row) {
    	//Log.e(PRINCIPAL, "valor de light no drawLight"+column+" "+row+" = "+light[column][row]);
        if (light[column][row] == ON) {
        	square[column][row].setImageResource(R.drawable.on);
        } else if (light[column][row] == OFF) {
        	square[column][row].setImageResource(R.drawable.off);
        }
        
   }
 
    
    /**
     * Método responsável de calcular quais dever�o acender e apagar dos lados visinhos, verificando se o lado realmente existe.
     */
    public void calclado(int y, int x){
    	if(y-1 >=0){
    		if(light[y-1][x] == OFF){
        		light[y-1][x] = ON;
    		}else{
    			light[y-1][x] = OFF;
    		}	
    	}    	
		if(x-1 >= 0){
			if(light[y][x-1] == OFF){
				light[y][x-1] = ON;
			}else{
				light[y][x-1] = OFF;
			}
		}
		if(x+1 <= 4){
			if(light[y][x+1] == OFF){
				light[y][x+1] = ON;
			}else{
				light[y][x+1] = OFF;
			}
		}
		if(y+1 <= 4){
			if(light[y+1][x] == OFF){
				light[y+1][x] = ON;
			}else{
				light[y+1][x] = OFF;
			}
		}		
		if(light[y][x] == OFF){
			light[y][x] = ON;
		}else{
			light[y][x] = OFF;
		}
    }
    /**
     * Método responsável por contar as lâmpadas acesas e apagadas e também definir se o jogador ganhou ou não
     */
    void countLight() {
        counterOn = 0;
        counterOff = 0;
        for (int i = 0; i < 5; i++) {
             for (int j = 0; j < 5; j++) {
                  if(light[i][j] == ON) counterOn++;
                  if(light[i][j] == OFF) counterOff++;
             }
        }
        
        valueOn.setText(String.valueOf(counterOn));
        valueOff.setText(String.valueOf(counterOff));
        
        if (counterOn == 25) {
        	chronometer.stop();//para o cronometro
        	String elipsedTime = chronometer.getText().toString();//será passado futuramente para o dialog que vai salvar o record
        	dialogVictory();
        }
   }
    
private void dialogVictory(){   	 
    	
    	final Dialog dialog = new Dialog(this);
    	
    	dialog.setContentView(R.layout.dialog_victory);
    	dialog.setTitle(R.string.congratulation);

    	TextView time = (TextView) dialog.findViewById(R.id.time);
    	TextView timeElipsed = (TextView) dialog.findViewById(R.id.time_elipsed);
    	TextView record = (TextView) dialog.findViewById(R.id.record);
    	TextView tName = (TextView) dialog.findViewById(R.id.name);
    	
    	final EditText etName = (EditText) dialog.findViewById(R.id.et_name);
    	
    	final Button ok = (Button) dialog.findViewById(R.id.ok);
    	final Button playAgain = (Button) dialog.findViewById(R.id.play);
    	
    	
    	
    	final Intent i = new Intent(this, RecordsView.class);
    	
    	ok.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				String name = etName.getText().toString();
		    	int numberOfMoves = 8;//teste
				saveRecord(name, numberOfMoves);				
				dialog.dismiss();//faz o dialog desaparecer
				
				
				startActivity(i);
				
				
		    	
		    	
				
				
				
				
			}
		});
    	
    	playAgain.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				
				//TODO: RESETAR O TEMPO
				dialog.dismiss();
				
			}
		});
	
	    	
    dialog.show();
    	
    	

	}

	@Override
	protected void onPause() {
		
		chronometer.stop();//para o cronometro
		chronometer.setBase(SystemClock.elapsedRealtime());
		
		super.onPause();
	}
	
	/** método que receberá de outro método os valores do banco por ordem Ascendente(ASC) e atualizará o registro de acordo com seu valor
	 * 
	 * @param vector
	 * @param novoRecord
	 */
	private void orderDatabase(int vector[], int novoRecord){
		
		for(int i = 0; i < 10; i++){
			
			if(novoRecord < vector[9]){//ultimo valor do vetor
				return;//testar esse return, não sei direito pra que ele serve
			}else if((i==0) && (novoRecord >= vector[i])){//primeiro valor do vetor
				//TODO: MÉTODO QUE ATUALIZA O BANCO NA POSIÇÃO i
				break;
			}else if((novoRecord >= vector[i]) && (novoRecord<=vector[i+1])){//
				//TODO: MÉTODO QUE ATUALIZA O BANCO NA POSIÇÃO i
			}
		}
		
	}
	
	
	
	private void saveRecord(String name, int numberMoves){
		
		mDbHelper.createRecord(name, numberMoves);//cria um novo record
	}
	
    
}